package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.dm.jsp.common.ExcelUtil;
import com.liangtian.mdm.material.model.WlLbmb;
import com.liangtian.mdm.material.model.WlLbmbTzlfh;
import com.liangtian.mdm.material.model.WlLbmbtzl;
import com.liangtian.mdm.material.service.WlLbmbService;
import com.liangtian.mdm.material.service.WlLbmbtzlService;
import com.liangtian.mdm.material.service.WlLbmbtzlqzService;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.util.ConstantBean;
import com.liangtian.mdm.util.ExportUtil;
import com.liangtian.mdm.util.IoUtil;
import com.liangtian.mdm.util.TemplateName;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/wlLbmbtzlController")
public class WlLbmbtzlController extends BaseController {

    @Autowired
    private WlLbmbtzlService wlLbmbtzlService;

    @Autowired
    private WlLbmbtzlqzService wlLbmbtzlqzService;

    // 日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @Autowired
    JdbcDao jdbcDao;

    private ExcelImport excelImport = new ExcelImport();

    @Autowired
    private WlLbmbService wlLbmbService;

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbtzlListCountByCond", method = RequestMethod.POST)
    public ResultObject getWlLbmbtzlListCountByCond(HttpServletRequest request, WlLbmbtzl tzl) {
        int count = wlLbmbtzlService.getWlLbmbtzlListCountByCond(tzl);
        int f = count == 0 ? 1 : 0;
        ResultObject result = new ResultObject(f, "成功", "失败");
        return result;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @ResponseBody
    @RequestMapping(value = "/getWlLbmbtzlListByCond", method = RequestMethod.POST)
    public JSONObject getWlLbmbtzlListByCond(HttpServletRequest request, WlLbmbtzl tzl) {
        Map paramMap = RequestUtils.paramToMap(request, WlLbmbtzl.class, false);
        PageInfo pageInfo = wlLbmbtzlService.getWlLbmbtzlListByCond(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @RequestMapping(value = "/getWlLbmbtzlById", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getWlLbmbtzlById(HttpServletRequest request, WlLbmbtzl tzl) {
        Map<String, Object> tzlResult = wlLbmbtzlService.getWlLbmbtzlById(tzl);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mbtzl", tzlResult);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbTzlfhByCond", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlLbmbTzlfhByCond(HttpServletRequest request, WlLbmbTzlfh fh) {
        Map paramMap = RequestUtils.paramToMap(request, WlLbmbTzlfh.class, false);
        PageInfo pageInfo = wlLbmbtzlService.getWlLbmbTzlfhByCond(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getWlLbmbTzlJldwByCond", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getWlLbmbTzlJldwByCond(HttpServletRequest request, WlLbmbTzlfh fh) {
        Map paramMap = RequestUtils.paramToMap(request, WlLbmbTzlfh.class, false);
        PageInfo pageInfo = wlLbmbtzlService.getWlLbmbTzlJldwByCond(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getTzlFhAddCount", method = RequestMethod.POST)
    public JSONObject getTzlFhAddCount(HttpServletRequest request, WlLbmbTzlfh tzlfh) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = wlLbmbtzlService.getTzlFhAddCount(tzlfh);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @RequestMapping(value = "/insertWlLbmbTzlfh", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertWlLbmbTzlfh(WlLbmbTzlfh tzlfh, HttpServletRequest request) {
        // 获取当前日期
        Date date = new Date();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);

        tzlfh.setCreator_id(user.getUserId().intValue());
        tzlfh.setCreator_name(user.getUserName());
        int count = wlLbmbtzlService.insertWlLbmbTzlfh(tzlfh);
		/*// ==============================记录操作日志start===============================================
		SysLog sysLog = new SysLog();
		sysLog.setUserName(user.getUserName());
		sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
		sysLog.setOperationDate(date);
		if (count > 0) {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",添加特征量指定类型的符号成功");
		} else {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",添加特征量指定类型的符号失败");
		}
		sysLogServiceImpl.insertLog(sysLog);
		// ==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增物料类别模板特征量符号[" + tzlfh.getFhname() + "][" + tzlfh.getFh_type() + "]",
                SysLogEnum.WL_LBMB_TZLFH.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteWlLbmbTzlfh", method = RequestMethod.POST)
    public ResultObject deleteWlLbmbTzlfh(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;
        Map<String, Object> map = new HashMap<>();
        map.put("idList", ids.split(","));
        int ret = wlLbmbtzlService.deleteWlLbmbTzlfh(map);
        int f = ret > 0 ? 1 : 0;
        //记录日志
        SysLogUtil.insertLog("删除物料类别模板特征量符号[" + ids + "]",
                SysLogEnum.WL_LBMB_TZLFH.getCode(), SysLogEnum.SC.getCode(), request);
        ResultObject result = new ResultObject(f, "删除成功", "删除失败");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getAddMbTzlCountByTzlmc", method = RequestMethod.POST)
    public JSONObject getAddMbTzlCountByTzlmc(HttpServletRequest request, WlLbmbtzl tzl) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = wlLbmbtzlService.getAddMbTzlCountByTzlmc(tzl);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @RequestMapping(value = "/insertWlLbmbtzl", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertWlLbmbtzl(WlLbmbtzl tzl, HttpServletRequest request) {
        // 获取当前日期
        Date date = new Date();
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);

        WlLbmbtzl mbtzl = new WlLbmbtzl();
        mbtzl.setWl_lbmb_id(tzl.getWl_lbmb_id());
        int num = wlLbmbtzlService.getWlLbmbtzlListCountByCond(mbtzl);
        int xh = 0;
        if (0 == num) {
            xh = num + 1;
        } else {
            int mx = wlLbmbtzlService.getTzlMaxXh(mbtzl);
            xh = mx + 1;
        }
        tzl.setXh(xh);
        if (ObjectUtils.isEmpty(tzl.getQzsx())) {
            tzl.setQzsx(0);
        }
        if (ObjectUtils.isEmpty(tzl.getQzxx())) {
            tzl.setQzxx(0);
        }
        tzl.setCreator_id(String.valueOf(user.getUserId()));
        tzl.setCreator_name(user.getUserName());
        int count = wlLbmbtzlService.insertWlLbmbtzl(tzl);
		/*// ==============================记录操作日志start===============================================
		SysLog sysLog = new SysLog();
		sysLog.setUserName(user.getUserName());
		sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
		sysLog.setOperationDate(date);
		if (count > 0) {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",添加模板特征量成功");
		} else {
			sysLog.setOperationContent("用户【" + ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()
					+ "】于" + DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss") + ",添加模板特征量失败");
		}
		sysLogServiceImpl.insertLog(sysLog);
		// ==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增物料类别模板特征量[" + tzl.getTzlmc() + "]",
                SysLogEnum.WL_LBMB_TZL.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getMbTzlById", method = RequestMethod.POST)
    public String getMbTzlById(WlLbmbtzl tzl) {
        WlLbmbtzl mbtzl = null;
        try {
            mbtzl = wlLbmbtzlService.getMbTzlById(tzl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(mbtzl);
    }

    @ResponseBody
    @RequestMapping(value = "/checkEditMbTzlCount", method = RequestMethod.POST)
    public JSONObject checkEditMbTzlCount(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        int count = 0;
        try {
            count = wlLbmbtzlService.checkEditMbTzlCount(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("count", count);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/updateWlLbmbtzl", method = RequestMethod.POST)
    public JSONObject updateWlLbmbtzl(WlLbmbtzl tzl) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            if ("0".equals(tzl.getXxsxbz())) {
                tzl.setQzsx(0);
                tzl.setQzxx(0);
            }
            wlLbmbtzlService.updateWlLbmbtzl(tzl);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/updateWlLbmbtzlByMap", method = RequestMethod.POST)
    public ResultObject updateWlLbmbtzlByMap(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (ids == null || "".equals(ids))
            return null;
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        Map<String, Object> map = new HashMap<>();
        map.put("idList", ids.split(","));
        int ret = wlLbmbtzlService.updateWlLbmbtzlByMap(map);
        //记录日志
        SysLogUtil.insertLog("删除物料类别模板特征量符号[" + ids + "]",
                SysLogEnum.WL_LBMB_TZLFH.getCode(), SysLogEnum.SC.getCode(), request);
        if (ret > 0) {
            int delfh = wlLbmbtzlService.deleteWlLbmbTzlfhByTzlid(map);
            if (delfh > 0) {
                map.put("update_uid", user.getUserId());
                map.put("update_name", user.getUserName());
                int delqz = wlLbmbtzlqzService.updateWlLbmbtzlqzByMbtzlidMap(map);
                if (delqz > 0) {
                    ResultObject result = new ResultObject(1, "删除成功", "删除失败");
                    return result;
                } else {
                    ResultObject result = new ResultObject(1, "删除成功", "删除失败");
                    return result;
                }
            } else {
                ResultObject result = new ResultObject(1, "删除成功", "删除失败");
                return result;
            }
        } else {
            ResultObject result = new ResultObject(0, "删除成功", "删除失败");
            return result;
        }
    }

    /**
     * 导出特征量模板
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "wlLbmbTzlExport", method = RequestMethod.GET)
    @ResponseBody
    public String wlLbmbTzlExport(HttpServletResponse response, HttpServletRequest request) {
        String path = IoUtil.getTemplatePath();
        String fileName = TemplateName.TZL_TEMPLATE;//服务器上存的文件名
        String uploadFileName = "特征量创建-维护模板";//给用户下载看到的文件名
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
        return null;
		/*InputStream inStream = null;
		String fileName = null;
		OutputStream outStream = null;
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
			path=path.replace('/', '\\'); // 将/换成\
			path=path.replace("classes\\", ""); //去掉class\
			path=path.replace("file:\\", ""); //file:\
			path += "doc\\dataTemplate";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/vnd.ms-excel");
			fileName = "特征量创建-维护模板.xlsx";
			response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
			File file = new File(path,fileName);
			inStream = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			int len;
			outStream = response.getOutputStream();
			while((len = inStream.read(bytes)) != -1 ) {
				outStream.write(bytes, 0, len);
	        }
			outStream.flush();
			outStream.close();
			outStream = null;
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(inStream != null){
				try{inStream.close();}
				catch(Exception e){}
			}
		}
		return null;*/
    }

    /**
     * 导入物料模板特征量
     *
     * @param modelId
     * @param tableName
     * @return
     */
    @RequestMapping(value = "excelImport", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject excelImport(HttpServletResponse response, HttpServletRequest request) {
        ResultObject result = null;
        try {
            String tableName = request.getParameter("tableName");
            String mbid = request.getParameter("wl_lbmb_id");
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            //记录日志
            SysLogUtil.insertLog("导入物料模板特征量",
                    SysLogEnum.WL_LBMB_TZLFH.getCode(), SysLogEnum.PD.getCode(), request);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = excelImport.getWorkbook(uploadFile);
            int sheetNum = 0;
            // 得到sheet总数
            sheetNum = book.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = book.getSheetAt(i);
                List<Object[]> valueList = excelImport.read(sheet);
                // 插入数据
                if (valueList != null && valueList.size() > 0) {
                    result = checkImportList(valueList, tableName, mbid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * * <p>Title: 校验用户输入的数据</p>
     * <p>Company:@param valueList
     * <p>Company:@param tableName
     * <p>Company:@param conn
     * <p>Company:@return </p>
     */
    @RequestMapping(value = "/checkImportList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject checkImportList(List<Object[]> valueList, String tableName, String lbmbid) {
        ExcelUtil eu = new ExcelUtil();
        String fileName = "";
        ResultObject resuObj = null;
        StringBuffer sb = new StringBuffer();//声明拼接符
        valueList.remove(0);
        if (0 != valueList.size() && null != valueList) {
            for (int j = 0; j < valueList.size(); j++) {//获取用户将导入的数据n条
                String[] row = (String[]) valueList.get(j);//获取行
                for (int k = 0; k < row.length; k++) {
                    String cell = row[k];//获取每固定行一列（0,0）
                    sb.append(checkColumn(j, k, cell, row, lbmbid));
                }

            }
        } else {
            sb.append("@@@@" + "请在模板中填写需要导入的数据！");
        }

        if (sb.toString().equals("")) {
            String[] headArray = {"USER_NAME", "USER_ACCOUNT", "USER_EMAIL", "USER_PHONE", "USER_TELEPHONE", "ORGANIZATION_ID"};
            List<String> sqls = genSql(tableName, valueList, headArray, lbmbid);
            boolean sucess = jdbcDao.executeSqlList(sqls, true);
            if (sucess) {
                resuObj = new ResultObject("true", "导入成功!");
            }
        } else {
            fileName = "wllbtzlImportError" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".txt";
            try {
                ExportUtil.errTxt(sb.toString(), fileName);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
			/*try {
				fileName="特征量批量导入"+"@@@@"+new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+".txt";
				eu.errTxt(sb.toString(), fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}*/
            resuObj = new ResultObject("false", fileName);
        }
        return resuObj;
    }

    public String checkColumn(int row, int column, String cell, String[] coll, String lbmbid) {
        StringBuffer sb = new StringBuffer();//声明拼接符
        //校验每行数据的每一列，错误的拼接成string，正确的不拼接
        if (column == 0) {//说明是第一列（校验特征量名称）
            if (cell.equals("") || cell == null || cell.equals(" ")) {//如果数据为空
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量名称为空！");
            } else {
                WlLbmbtzl tzl = new WlLbmbtzl();
                tzl.setTzlmc(cell);
                tzl.setWl_lbmb_id(lbmbid);
                int count = wlLbmbtzlService.getAddMbTzlCountByTzlmc(tzl);
                if (count > 0) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量名称已存在!");
                }
            }

        } else if (column == 2) {//说明是第二列（校验前置是否可空）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,前置是否可空为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,前置是否可空输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 3) {//说明是第二列（校验特征量是否必填）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否必填为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否必填输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 4) {//说明是第二列（校验特征量是否必选）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否必选为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否必选输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 5) {//说明是第二列（校验特征量是否数字）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否数字为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,特征量是否数字输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 6) {//说明是第二列（校验是否使用取值上下限）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,是否使用取值上下限为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,是否使用取值上下限输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 7) {//说明是第二列（校验上限）
            if ("1".equals(coll[5])) {
                if (cell.equals("") || cell == null || cell.equals(" ")) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,上限为空！");
                } else if (Integer.parseInt(cell) < 0) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,上限为正整数！");
                }
            }
        } else if (column == 8) {//说明是第二列（校验下限）
            if ("1".equals(coll[5])) {
                if (cell.equals("") || cell == null || cell.equals(" ")) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,下限为空！");
                } else if (Integer.parseInt(cell) < 0) {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,下限为正整数！");
                } else {
                    if (Integer.parseInt(cell) >= Integer.parseInt(coll[7])) {
                        sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,上下限设置不合理,下限不可大于等于上限！");
                    }
                }
            }
        } else if (column == 9) {//说明是第二列（校验后置符号是否可空）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,后置符号是否可空为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,后置符号是否可空输入错误,请按照Excel标注填写！");
                }
            }
        } else if (column == 10) {//说明是第二列（校验计量单位长描述）
            if (cell.equals("") || cell == null || cell.equals(" ")) {
                sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,计量单位长描述为空！");
            } else {
                if ("0".equals(cell) || "1".equals(cell)) {

                } else {
                    sb.append("@@导入数据第" + (row + 2) + "行,第" + (column + 1) + "列,计量单位长描述输入错误,请按照Excel标注填写！");
                }
            }
        }
        return sb.toString();

    }

    /*
     * @description:向数据库表中插入数据(1000行插入一次)
     * @param tableName,conn,sqlStr,subList,headArray
     * @return
     * @time:2016年9月07日
     */
    public List<String> genSql(String tableName, List<Object[]> subList, String[] headArray, String lbmbid) {
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);

        List<String> sqls = new ArrayList<String>();
        // 获取值集合
        for (int j = 0; j < subList.size(); j++) {
            StringBuffer sb = new StringBuffer("");
            sb.append(" insert into " + tableName + " (ID,")
                    .append("TZLMC,REMARK,QZFHSFKK,NECESSARY,CHOOSEABLE,QZSFWSZ,XXSXBZ,QZSX,QZXX,HZFHSFKK,JLDWLMS,")
                    .append("WL_LBMB_ID,WL_LB_ID,LBBM,XH,CREATOR_ID,CREATOR_NAME,CREATE_TIME,VERSION,")
                    .append("STATUS,STATE)")
                    .append(" VALUES( WL_LBMB_TZL_seq.nextval,");

            String[] row = (String[]) subList.get(j);
            WlLbmb lbmb = new WlLbmb();
            lbmb.setId(lbmbid);
            WlLbmb wllbmb = wlLbmbService.getWlLbmbById(lbmb);
            sb.append("'").append(row[0]).append("',").append("'").append(row[1].trim()).append("',")
                    .append("'").append(row[2].trim()).append("',").append("'").append(row[3].trim()).append("',")
                    .append("'").append(row[4].trim()).append("',").append("'").append(row[5].trim()).append("',")
                    .append("'").append(row[6].trim()).append("',");
            if ("1".equals(row[6])) {
                if (StringUtils.isEmpty(row[7].trim())) {
                    sb.append(" 0,");
                } else {
                    sb.append("").append(row[7]).append(",");
                }
                if (StringUtils.isEmpty(row[8].trim())) {
                    sb.append(" 0,");
                } else {
                    sb.append("").append(row[8]).append(",");
                }
            } else {
                sb.append("").append(row[7].trim()).append(",").append("").append(row[8].trim()).append(",");
            }

            sb.append("'").append(row[9]).append("',").append("'").append(row[10]).append("',")
                    .append("'").append(wllbmb.getId()).append("',").append("'").append(wllbmb.getWl_lb_id()).append("',")
                    .append("'").append(wllbmb.getLbbm()).append("',");

            WlLbmbtzl mbtzl = new WlLbmbtzl();
            mbtzl.setWl_lbmb_id(wllbmb.getId());
            int num = wlLbmbtzlService.getWlLbmbtzlListCountByCond(mbtzl);
            int xh = num + 1;

            sb.append("").append(xh).append(",").append("'").append(user.getUserId()).append("',")
                    .append("'").append(user.getUserName()).append("', sysdate, 0, '1', '4' )");

            sqls.add(sb.toString());
            System.out.print(sb.toString());
        }
        return sqls;
    }

    /*
     * 2017-06-29
     * jyh
     * 错误日志下载抽取至LogErrorsController中
     */
    /**
     * * <p>Title: 导入数据，错误文档</p>
     * <p>Company:@param response
     * <p>Company:@param request </p>
     */
    /*@RequestMapping(value = "downLoadErr", method = RequestMethod.POST)
    @ResponseBody
    public void downLoadErr(HttpServletResponse response,HttpServletRequest request){
    	String fileName = request.getParameter("err_fileName");
		String path = WlLbmbtzlController.class.getProtectionDomain().getCodeSource()  
                .getLocation().getPath();
		String file=path.substring(1, path.indexOf("/WEB-INF/classes"))+"/error_text/"+fileName;
		System.out.println("file:"+file);
		try {
			InputStream inStream = new FileInputStream(file);
			if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
			     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
			}else{
			     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
			}
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
			// 循环取出流中的数据
			byte[] b = new byte[100];
			int len;
			OutputStream output=response.getOutputStream();
			while ((len = inStream.read(b)) > 0)
				output.write(b, 0, len);
			
			output.flush();
			output.close();
			inStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/

    /**
     * 取关联特征量
     *
     * @return
     * @author jiangyh
     * @date 2016-12-28
     */
    @RequestMapping(value = "getGlTzl", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getGlTzl(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String main_std_tzl_id = request.getParameter("tzlId");
        String wl_lbmb_id = request.getParameter("wl_lbmb_id");
        Map<String, Object> cond = new HashMap<>();
        cond.put("wl_lbmb_id", wl_lbmb_id);
        cond.put("main_std_tzl_id", main_std_tzl_id);
        List<WlLbmbtzl> tzl_lst = wlLbmbtzlService.getWlLbmbtzlByCond(cond);
        if (!CollectionUtils.isEmpty(tzl_lst)) {
            jsonObject.put("tzl_lst", tzl_lst);
            jsonObject.put("success", true);
        } else {
            jsonObject.put("success", false);
        }
        return jsonObject;
    }

}
